package com.webcams.core.xmlparsor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;

import com.webcams.core.resorts.DatabaseSQLite;
import com.webcams.core.resorts.Resort;


public class Parsor extends DefaultHandler{

	// ===========================================================
	// Fields
	// ===========================================================
	private static final int IO_BUFFER_SIZE = 4 * 1024;

	private DatabaseSQLite database;
	private Context context;

	public Parsor(Context context, DatabaseSQLite database){
		this.context = context;
		this.database = database;
	}

	// ===========================================================
	// Methods
	// ===========================================================
	@Override
	public void startDocument() throws SAXException {
		// Nothing to do
	}

	@Override
	public void endDocument() throws SAXException {
		// Nothing to do
	}

	/** Gets be called on opening tags like:
	 * <tag>
	 * Can provide attribute(s), when xml was like:
	 * <tag attribute="attributeValue">*/
	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		if (localName.equals("station")) {


			int logoLastUpdate = Integer.decode(atts.getValue("logolastupdate"));

			String logoFileName = "logo_"+Integer.decode(atts.getValue("id"))+".jpg";
			String logoFilePathLocal = Resort.localLogoFolder+logoFileName;
			File logoFileLocal = new File(context.getExternalFilesDir(null), logoFilePathLocal);
			if(logoFileLocal == null || logoLastUpdate > logoFileLocal.lastModified()/1000) {
				try {
					String logoFilePathDist = Resort.urlWebAcces+Resort.distLogoFolder+logoFileName;
					URL url = new URL(logoFilePathDist);

					HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

					urlConnection.setRequestMethod("GET");
					urlConnection.setDoOutput(true);
					urlConnection.connect();

					File mapFolder = logoFileLocal.getParentFile();
					if(!mapFolder.exists()){
						mapFolder.mkdirs();
					}

					FileOutputStream fileOutput = new FileOutputStream(logoFileLocal);

					BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
					
					final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
					BufferedOutputStream out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
		            
					copy(inputStream, out);
					out.flush();
					
					fileOutput.write(dataStream.toByteArray());
				} catch (MalformedURLException e) {
					e.printStackTrace();
					logoLastUpdate = 0;
				} catch (IOException e) {
					e.printStackTrace();
					logoLastUpdate = 0;
				}

			}

			database.insertOrUpdateResort(Integer.decode(atts.getValue("id")), 
					atts.getValue("name"), Integer.decode(atts.getValue("dep")), 
					Integer.decode(atts.getValue("webcamssize")), Float.parseFloat(atts.getValue("lat")), 
					Float.parseFloat(atts.getValue("lon")), Integer.decode(atts.getValue("mapsize")), 
					Integer.decode(atts.getValue("maplastupdate")), 
					logoLastUpdate,
					atts.getValue("d1amico"), Float.parseFloat(atts.getValue("d1amte")), 
					atts.getValue("d1pmico"), Float.parseFloat(atts.getValue("d1pmte")),
					StringEscapeUtils.unescapeHtml(atts.getValue("d1desc")), 
					atts.getValue("d2amico"), Float.parseFloat(atts.getValue("d2amte")), 
					atts.getValue("d2pmico"), Float.parseFloat(atts.getValue("d2pmte")),
					StringEscapeUtils.unescapeHtml(atts.getValue("d2desc")), 
					atts.getValue("d3amico"), Float.parseFloat(atts.getValue("d3amte")), 
					atts.getValue("d3pmico"), Float.parseFloat(atts.getValue("d3pmte")),
					StringEscapeUtils.unescapeHtml(atts.getValue("d3desc")),
					Integer.decode(atts.getValue("nextupdate")));

		}
	}

	/** Gets be called on closing tags like:
	 * </tag> */
	@Override
	public void endElement(String namespaceURI, String localName, String qName)
	throws SAXException {
	}
	
    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
}